package org.example.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.service.AudioService;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 有道词典API实现的音频服务
 * 使用有道词典API获取单词的美式和英式发音
 */
@Service
@Slf4j
public class YoudaoAudioService implements AudioService {

    // 有道词典API的基础URL
    private static final String YOUDAO_VOICE_API_URL = "https://dict.youdao.com/dictvoice";

    // 发音类型：1=英式发音，2=美式发音
    private static final String TYPE_BRITISH = "1";
    private static final String TYPE_AMERICAN = "2";

    @Override
    public String getAmericanPronunciationUrl(String word) {
        return buildPronunciationUrl(word, TYPE_AMERICAN);
    }

    @Override
    public String getBritishPronunciationUrl(String word) {
        return buildPronunciationUrl(word, TYPE_BRITISH);
    }

    /**
     * 构建发音URL
     *
     * @param word 英文单词
     * @param type 发音类型：1=英式，2=美式
     * @return 发音音频的URL
     */
    private String buildPronunciationUrl(String word, String type) {
        if (word == null || word.trim().isEmpty()) {
            log.warn("尝试获取空单词的发音");
            return "";
        }

        try {
            // 对单词进行URL编码
            String encodedWord = URLEncoder.encode(word.trim(), StandardCharsets.UTF_8.name());

            // 构建URL
            String url = UriComponentsBuilder.fromHttpUrl(YOUDAO_VOICE_API_URL)
                    .queryParam("audio", encodedWord)
                    .queryParam("type", type)
                    .build()
                    .toUriString();

            log.debug("为单词 '{}' 生成{}发音URL: {}",
                    word,
                    TYPE_AMERICAN.equals(type) ? "美式" : "英式",
                    url);

            return url;
        } catch (UnsupportedEncodingException e) {
            log.error("URL编码单词时出错: {}", e.getMessage(), e);
            return "";
        }
    }
}
